package com.lovepick;

import java.util.List;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;

import com.lovepick.adapter.OrderInfoAdapter;
import com.lovepick.bean.Order;
import com.lovepick.bean.OrderInfo;
import com.lovepick.fragment.ManageFragment;
import com.lovepick.fragment.MsgFragment;
import com.lovepick.fragment.MsgListFragment;
import com.lovepick.fragment.OrderFragment;
import com.lovepick.fragment.OrderInfoFragment;
import com.lovepick.fragment.UserInfoFragment;
import com.lovepick.http.GetNewMsgService;
import com.lovepick.http.GetOrderService;
import com.lovepick.util.BaseUtils;
import com.lovepick.util.Constant;
import com.lovepick.util.IRecmdListener;

public class MainActivity extends FragmentActivity implements IRecmdListener,
		MsgListFragment.OnMsgListItemClickListener,
		ManageFragment.OrderOperationListener
{
	private static final String TAG = "MainActivity";
	public static final String TAB_TAG_HOME = "home";
	public static final String TAB_TAG_PINCHE = "pinche";
	public static final String TAB_TAG_MANAGE = "manage";
	public static final String TAB_TAG_MESSAGE = "message";
	public static final String TAB_TAG_USER = "user";
	public static final String TAB_TAG_MAP = "map";

	private static final String SELECTED_ITEM = "selected_item";
	//private static final int NAV_ITEM_HOME = 0;
	private static final int NAV_ITEM_PINCHE = 0;
	private static final int NAV_ITEM_MANAGE = 1;
	private static final int NAV_ITEM_MESSAGE = 2;
	private static final int NAV_ITEM_USER = 3;

	private MainReceiver mReceiver = null;
	private NotificationManager mNotificationManager = null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		Log.i(TAG, "---onCreate---");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);

		actionBar.addTab(actionBar.newTab().setText(R.string.title_tab_pick).setTabListener(
				new TabListener<OrderFragment>(this, TAB_TAG_PINCHE, OrderFragment.class)));
		actionBar.addTab(actionBar.newTab().setText(R.string.title_tab_manage).setTabListener(
				new TabListener<ManageFragment>(this, TAB_TAG_MANAGE, ManageFragment.class)));
		//actionBar.addTab(actionBar.newTab().setText(R.string.title_tab_manage).setTabListener(
			//	new TabListener<ManageFragment>(this, TAB_TAG_MANAGE, ManageFragment.class)));
		actionBar.addTab(actionBar.newTab().setText(R.string.title_tab_message).setTabListener(
				new TabListener<MsgListFragment>(this, TAB_TAG_MESSAGE, MsgListFragment.class)));
		actionBar.addTab(actionBar.newTab().setText(R.string.title_tab_user).setTabListener(
				new TabListener<UserInfoFragment>(this, TAB_TAG_USER, UserInfoFragment.class)));

		mReceiver = new MainReceiver();
		IntentFilter msgFilter = new IntentFilter(Constant.ACTION_NEW_MSGS);
		registerReceiver(mReceiver, msgFilter);
		IntentFilter orderFilter = new IntentFilter(Constant.ACTION_ORDER);
		registerReceiver(mReceiver, orderFilter);

		SharedPreferences preferences = getSharedPreferences(Constant.PREFS,
				Context.MODE_PRIVATE);
		if (preferences.contains(SELECTED_ITEM))
		{
			actionBar.setSelectedNavigationItem(preferences.getInt(
					SELECTED_ITEM, NAV_ITEM_PINCHE));
		}
		else
		{
			actionBar.setSelectedNavigationItem(NAV_ITEM_PINCHE);
		}



		/*
		// 发送界面开启广播, 新消息获取服务会接收此广播
		Log.i(TAG, "MainActivity发送界面开启广播");
		Intent intent = new Intent(Constant.ACTION_MAIN_ON);
		Bundle value = new Bundle();
		value.putBoolean("flag", true);
		intent.putExtra("bundle", value);
		sendBroadcast(intent);
		*/
	}

	/*
	@Override
	protected void onNewIntent(Intent intent)
	{
		super.onNewIntent(intent);
		Bundle data = intent.getBundleExtra("bundle_msg");
		if (data != null)
		{
			mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			mNotificationManager.cancel(GetNewMsgService.NOTIFY_ID);
			getActionBar().setSelectedNavigationItem(NAV_ITEM_MESSAGE);
			GlobalApp.getInstance().setNumMsgNew(0);
		}
	}
	*/

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.menu_msg_service_start:
				Log.i(TAG, "start msg service");
				Intent service = new Intent(MainActivity.this, GetNewMsgService.class);
				startService(service);
				break;

			case R.id.menu_msg_service_stop:
				Log.i(TAG, "stop msg service");
				Intent service2 = new Intent(MainActivity.this, GetNewMsgService.class);
				stopService(service2);
				break;

			case R.id.menu_order_service_start:
				Log.i(TAG, "start order service");
				Intent orderService = new Intent(MainActivity.this, GetOrderService.class);
				Bundle data = new Bundle();
				data.putString(Constant.ARG_ROLE, GlobalApp.getInstance().getRole());
				orderService.putExtra("bundle", data);
				startService(orderService);
				break;

			case R.id.menu_order_service_stop:
				Log.i(TAG, "stop order service");
				Intent orderService2 = new Intent(MainActivity.this, GetOrderService.class);
				Bundle data2 = new Bundle();
				data2.putString(Constant.ARG_ROLE, GlobalApp.getInstance().getRole());
				orderService2.putExtra("bundle", data2);
				stopService(orderService2);
				break;

			case R.id.menu_logout:
				if (GlobalApp.getInstance().logout())
				{
					BaseUtils.showToast(this, R.string.logout_success);
					Intent login = new Intent(this, LoginActivity.class);
					startActivity(login);
					finish();
				}
				else
				{
					BaseUtils.showToast(this, R.string.logout_fail);
				}
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		IntentFilter msgFilter = new IntentFilter(Constant.ACTION_NEW_MSGS);
		registerReceiver(mReceiver, msgFilter);
		IntentFilter orderFilter = new IntentFilter(Constant.ACTION_ORDER);
		registerReceiver(mReceiver, orderFilter);

		/*
		// 发送界面开启广播, 新消息获取服务会接收此广播
		Log.i(TAG, "MainActivity发送界面开启广播");
		Intent intent = new Intent(Constant.ACTION_MAIN_ON);
		Bundle value = new Bundle();
		value.putBoolean("flag", true);
		intent.putExtra("bundle", value);
		sendBroadcast(intent);
		*/
	}

	@Override
	public void onPause()
	{
		super.onPause();
		unregisterReceiver(mReceiver);

		/*// 发送界面关闭广播, 新消息获取服务会接收此广播
		Log.i(TAG, "MainActivity发送界面关闭广播");
		Intent intent = new Intent(Constant.ACTION_MAIN_ON);
		Bundle value = new Bundle();
		value.putBoolean("flag", false);
		intent.putExtra("bundle", value);
		sendBroadcast(intent);*/
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		if (GlobalApp.getInstance().getMapManager() != null)
		{
			GlobalApp.getInstance().getMapManager().destroy();
		}

		// 保存当前选中的tab项
		SharedPreferences preferences = getSharedPreferences(Constant.PREFS, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putInt(SELECTED_ITEM, getActionBar().getSelectedNavigationIndex());
		editor.commit();
		Log.i(TAG, "mapManager destroyed.");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
		{
			finish();
		}
		return true;
	}

	public class TabListener<T extends Fragment> implements ActionBar.TabListener
	{
		private final FragmentActivity mActivity;
		private final String mTag;
		private final Class<T> mClass;
		private final Bundle mArgs;
		private Fragment mFragment;

		public TabListener(FragmentActivity activity, String tag, Class<T> clz)
		{
			this(activity, tag, clz, null);
		}

		public TabListener(FragmentActivity activity, String tag, Class<T> clz, Bundle args)
		{
			mActivity = activity;
			mTag = tag;
			mClass = clz;
			mArgs = args;

			// 检测当前tab是否已经有一个fragment, 有可能是从之前保存的状态中恢复的;
			// 如果有, deactive it.
			mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
			if (mFragment != null && !mFragment.isDetached())
			{
				android.support.v4.app.FragmentTransaction ft =
						mActivity.getSupportFragmentManager().beginTransaction();
				ft.detach(mFragment);
				ft.commit();
			}

		}

		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft)
		{
			// TODO Auto-generated method stub
			Log.i(TAG, "##tab selected --> " + mClass.getName() + "##");
			if (tab.getPosition() == NAV_ITEM_MESSAGE)
			{
				tab.setText(R.string.title_tab_message);
			}
			if (null == mFragment)
			{
				mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
				mActivity.getSupportFragmentManager().beginTransaction()
				.add(R.id.container, mFragment, mTag).commit();
			}
			else
			{
				mActivity.getSupportFragmentManager().beginTransaction()
				.attach(mFragment).commit();
			}
		}

		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft)
		{
			// TODO Auto-generated method stub
			Log.i(TAG, "##tab unselected --> " + mClass.getName() + "##");
			if (mFragment != null)
			{
				mActivity.getSupportFragmentManager().beginTransaction().detach(mFragment).commit();
			}
		}

		@Override
		public void onTabReselected(Tab tab, FragmentTransaction ft)
		{
			// TODO Auto-generated method stub
			Log.i(TAG, "reseslected " + mClass.getName());
		}
	}

	public class MainReceiver extends BroadcastReceiver
	{

		@Override
		public void onReceive(Context context, Intent intent)
		{

			if (intent.getAction().equals(Constant.ACTION_NEW_MSGS))
			{
				Log.i(TAG, "## new msgs ##");
				MsgListFragment fragment = (MsgListFragment) getSupportFragmentManager().
						findFragmentByTag(TAB_TAG_MESSAGE);

				if (fragment != null && fragment.isVisible())
				{
					fragment.refresh();
				}
				else
				{
					getActionBar().getTabAt(NAV_ITEM_MESSAGE).setText(getString(R.string.title_tab_message) + "(new)");
				}
			}
			else if (intent.getAction().equals(Constant.ACTION_ORDER))
			{
				Log.i(TAG, "## get orders ##");
				String result = intent.getBundleExtra("bundle_order").getString(Constant.ARG_ORDER);
				ManageFragment fragment = (ManageFragment) getSupportFragmentManager().
						findFragmentByTag(TAB_TAG_MANAGE);
				//TabManageFragment fragment = (TabManageFragment)getSupportFragmentManager().
						//findFragmentByTag(TAB_TAG_MANAGE);
				if (fragment != null && fragment.isVisible())
				{
					fragment.refresh(result);
				}
			}
		}
	}

	// IRecmdListener
	@Override
	public void onGetRecmd(String role, Boolean isFromRelease, String result)
	{
		// TODO Auto-generated method stub
		Log.i(TAG, "---onGetRecmd---");
		Bundle bundle= new Bundle();
		bundle.putString(Constant.ARG_ROLE, role);
		bundle.putBoolean(Constant.ARG_IS_FROM_RELEASE, isFromRelease);
		bundle.putString(Constant.ARG_RECMD_JSON, result);
		Intent intent = new Intent(MainActivity.this, MapViewActivity.class);
		intent.putExtra("bundle", bundle);
		startActivity(intent);
	}

	// MsgListFragment.OnMsgListItemClickListener
	@Override
	public void onMsgListItemClick(int userID, String nickName)
	{
		// TODO Auto-generated method stub
		Bundle args = new Bundle();
		args.putInt(MsgFragment.ARG_USERID, userID);
		args.putString(MsgFragment.ARG_NICKNAME, nickName);
		Intent intent = new Intent(MainActivity.this, MsgActivity.class);
		intent.putExtra("bundle_msg", args);
		startActivity(intent);
	}

	// ManageFragment.OnOrderListener
	// 乘客, 查看已完成订单详情
	@Override
	public void onShowInfosForPassenger(String result)
	{
		// TODO Auto-generated method stub
		Log.i(TAG, "---onShowInfosForPassenger---");
		List<OrderInfo> infos = BaseUtils.getOrderInfos(result);
		if (infos != null)
		{
			OrderInfoAdapter adapter = new OrderInfoAdapter(this, infos, true);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.dialog_title_accept_infos);
			builder.setAdapter(adapter, null);
			builder.setPositiveButton(R.string.ok, null);
			builder.create().show();
		}
		else
		{
			BaseUtils.showToast(this, "获取订单信息失败!");
		}
	}

	// 司机, 查看申请乘客列表
	@Override
	public void onShowInfosForDriver(String result, Order order)
	{
		Log.i(TAG, "---onShowInfosForDriver---");
		// TODO Auto-generated method stub
		if (result.equals(Constant.JSON_ARRAY_EMPTY))
		{
			BaseUtils.showToast(this, R.string.no_passenger);
		}
		else
		{
			if (result.startsWith(Constant.JSON_ARRAY_START))
			{
				Bundle bundle = new Bundle();
				bundle.putString(OrderInfoFragment.ARG_INFOS, result);
				bundle.putString(OrderInfoFragment.ARG_SRC, order.getSrc());
				bundle.putString(OrderInfoFragment.ARG_DEST, order.getDest());
				bundle.putInt(OrderInfoFragment.ARG_ORDER_ID,
						order.getOrderID());
				bundle.putInt(OrderInfoFragment.ARG_USER_ID, order.getUserID());
				bundle.putInt(OrderInfoFragment.ARG_FREE_COUNT,
						order.getCount());

				Intent intent = new Intent(this, OrderInfoActivity.class);
				intent.putExtra("bundle_order_info", bundle);
				startActivity(intent);
			}
			else
			{
				BaseUtils.showToast(this, R.string.order_info_fail);
			}
		}
	}
}
